package com.papper.common.utils.tool;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

/**
 * @Author:Lajiao
 * @Date:2014年8月19日
 * @Time:下午2:52:49
 * @Description:文件操作工具类
 */
public class FileTool {
    public static String loadFileToString(String filename) throws IOException {
        BufferedReader br  = null;
        String         ret = null;

        try {
            File f = new File(filename);
            br = new BufferedReader(new FileReader(f));

            String       line = null;
            StringBuffer sb   = new StringBuffer((int) f.length());

            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }

            ret = sb.toString();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (Exception e) {
                }
            }
        }

        return ret;
    }

    public void newFolder(String folderPath) {
        try {
            String filePath = folderPath;
            filePath = filePath.toString();

            File myFilePath = new File(filePath);

            if (!myFilePath.exists()) {
                myFilePath.mkdir();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void newFile(String filePathAndName, String fileContent) {
        FileWriter resultFile = null;
        try {
            String filePath = filePathAndName;
            filePath = filePath.toString();

            File myFilePath = new File(filePath);
            File parent     = myFilePath.getParentFile();
            if (parent != null && !parent.exists()) {
                parent.mkdirs();
            }

            if (!myFilePath.exists()) {
                myFilePath.createNewFile();
            }

            resultFile = new FileWriter(myFilePath);
            String strContent = fileContent;
            resultFile.write(strContent);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (resultFile != null) {
                    resultFile.flush();
                    resultFile.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void delFile(String filePathAndName) {
        String filePath = filePathAndName;
        filePath = filePath.toString();

        File myDelFile = new File(filePath);
        myDelFile.delete();
    }

    public void delFolder(String folderPath) {
        delAllFile(folderPath);

        String filePath = folderPath;
        filePath = filePath.toString();

        File myFilePath = new File(filePath);
        System.out.println("=========" + myFilePath.getName());
        myFilePath.delete();
    }

    public void delAllFile(String path) {
        File file = new File(path);

        if (!file.exists()) {
            return;
        }

        if (!file.isDirectory()) {
            return;
        }

        String[] tempList = file.list();
        File     temp     = null;

        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }

            if (temp.isFile()) {
                System.out.println("=========" + temp.getName());
                temp.delete();
            }

            if (temp.isDirectory()) {
                delAllFile(path + File.separator + tempList[i]);
                delFolder(path + File.separator + tempList[i]);
            }
        }
    }

    public void copyFile(String oldPath, String newPath) throws IOException {
        int              byteread = 0;
        InputStream      inStream = null;
        FileOutputStream fs       = null;

        try {
            File oldfile = new File(oldPath);

            if (oldfile.exists()) {
                inStream = new FileInputStream(oldPath);
                fs = new FileOutputStream(newPath);

                byte[] buffer = new byte[1024 * 4];

                while ((byteread = inStream.read(buffer)) != -1) {

                    fs.write(buffer, 0, byteread);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new IOException(oldPath);
        } finally {
            try {
                if (fs != null) {
                    fs.close();
                }

                if (inStream != null) {
                    inStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void copyFolder(String oldPath, String newPath) throws Exception {
        FileInputStream  input  = null;
        FileOutputStream output = null;

        try {
            (new File(newPath)).mkdirs();

            File     a    = new File(oldPath);
            String[] file = a.list();
            File     temp = null;

            for (int i = 0; i < file.length; i++) {
                if (oldPath.endsWith(File.separator)) {
                    temp = new File(oldPath + file[i]);
                } else {
                    temp = new File(oldPath + File.separator + file[i]);
                }

                if (temp.isFile()) {
                    input = new FileInputStream(temp);
                    output = new FileOutputStream(newPath + File.separator + (temp.getName()).toString());

                    byte[] b = new byte[1024 * 5];
                    int    len;

                    while ((len = input.read(b)) != -1) {
                        output.write(b, 0, len);
                    }

                    output.flush();
                }

                if (temp.isDirectory()) {
                    if (!temp.getAbsolutePath().contentEquals(new StringBuffer(newPath.replace('/', '\\')))) {
                        copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception(oldPath + "," + newPath);
        } finally {
            try {
                if (output != null) {
                    output.close();
                }

                if (input != null) {
                    input.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void moveFile(String oldPath, String newPath) throws IOException {
        copyFile(oldPath, newPath);
        delFile(oldPath);
    }

    public void moveFolder(String oldPath, String newPath) throws Exception {
        copyFolder(oldPath, newPath);
        delFolder(oldPath);
    }

    public void modifyProp(String propFile, Map<?, ?> modifyProp) throws IOException {
        Properties proper = new Properties();

        FileInputStream finPut = new FileInputStream(propFile);
        proper.load(finPut);

        Iterator<?> keys = (Iterator<?>) modifyProp.keySet().iterator();

        while (keys.hasNext()) {
            String key   = (String) keys.next();
            String value = (String) modifyProp.get(key);
            System.out.println("key==" + key);
            System.out.println("value==" + value);
            proper.put(key, value);
        }

        FileOutputStream foutPut = new FileOutputStream(propFile);
        proper.store(foutPut, "");
    }

    public void modifyFile(String propFile, Map<?, ?> modifyProp) throws IOException {
        FileReader     fr = null;
        BufferedReader br = null;

        try {
            fr = new FileReader(propFile);
            br = new BufferedReader(fr);

            StringBuffer allProp = new StringBuffer();
            String       temp;
            String       key;
            String       value;
            int          end;

            while (true) {
                temp = br.readLine();

                if (temp == null) {
                    break;
                }

                end = temp.indexOf("=");

                if (end != -1) {
                    key = temp.substring(0, end);
                    value = (String) modifyProp.get(key);

                    if ((value != null) && !"#delete;".equals(value)) {
                        temp = key + "=" + value;
                        modifyProp.remove(key);
                    } else if ("#delete;".equals(value)) {
                        temp = "";
                        modifyProp.remove(key);
                    }
                }

                allProp.append(temp);
                allProp.append("\r\n");

            }

            Iterator<?> ite = modifyProp.keySet().iterator();

            while (ite.hasNext()) {
                key = (String) ite.next();
                value = (String) modifyProp.get(key);

                if (!"#delete;".equals(value)) {
                    allProp.append(key + "=" + value);
                    allProp.append("\r\n");
                }
            }

            PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(propFile)));
            pw.write(allProp.toString());
            pw.close();
        } catch (IOException e) {
            throw new IOException(propFile);
        } finally {
            if (br != null) {
                br.close();
            }

            if (fr != null) {
                fr.close();
            }
        }
    }

    public static BufferedReader getFile(String path) {
        try {
            FileInputStream   fr           = new FileInputStream(path);
            InputStreamReader is           = new InputStreamReader(fr, "UTF-8");
            BufferedReader    bufferReader = new BufferedReader(is);
            return bufferReader;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
